import json
import requests
from voice_assistant.config_manager import config_manager

# Flask API 客户端
class FlaskClient:
    def __init__(self, base_url=None):
        self.base_url = base_url or config_manager.get("server.flask_url")
        print(f"Using Flask server at {self.base_url}")
    
    def post(self, endpoint, **kwargs):
        url = f"{self.base_url}{endpoint}"
        try:
            response = requests.post(url, **kwargs)
            response.raise_for_status()
            return {"data": response.json(), "success": True}
        except Exception as e:
            print(f"POST请求失败: {str(e)}")
            return {"success": False, "error": str(e)}
    
    def get(self, endpoint):
        url = f"{self.base_url}{endpoint}"
        try:
            response = requests.get(url)
            response.raise_for_status()
            return {"data": response.json(), "success": True}
        except Exception as e:
            print(f"GET请求失败: {str(e)}")
            return {"success": False, "error": str(e)}

# API调用类
class SummaryAPI:
    @staticmethod
    def submit_task(text, flask_client=None):
        """提交总结任务API"""
        if flask_client is None:
            from voice_assistant.app import VoiceAssistantApp
            flask_client = VoiceAssistantApp().flask_client
            
        try:
            response = flask_client.post('/api/ai/summarize', 
                headers={'Content-Type': 'application/json'},
                data=json.dumps({"text": text})
            )
            print(response)
            
            if response["data"]["success"]:
                return response["data"]["data"]
            else:
                print(f"提交任务失败: {response.get('error', '未知错误')}")
                return {"task_id": None}
        except Exception as e:
            print(f"提交任务异常: {str(e)}")
            return {"task_id": None}
    
    @staticmethod
    def get_task_result(task_id, flask_client=None):
        """获取任务结果API"""
        if not task_id:
            return {"status": "failed", "error": "无效的任务ID"}
        
        if flask_client is None:
            from voice_assistant.app import VoiceAssistantApp
            flask_client = VoiceAssistantApp().flask_client
            
        try:
            response = flask_client.get(f"/api/ai/summarize/status/{task_id}")
            print(response)
            
            if response["data"]["success"]:
                data = response["data"]["data"]
                if(not data):
                    return {"status": "failed", "error": "任务未找到或结果为空"}
                
                status = data.get("status", "processing")
                
                if status == "completed":
                    return {
                        "status": "completed",
                        "result": data.get("result", "总结生成成功，但内容为空")
                    }
                elif status == "failed":
                    return {
                        "status": "failed",
                        "error": data.get("error", "总结生成失败")
                    }
                else:
                    return {"status": "processing", "progress": 50}
            else:
                return {"status": "failed", "error": response.get("error", "获取任务状态失败")}
        except Exception as e:
            print(f"获取任务状态异常: {str(e)}")
            return {"status": "failed", "error": str(e)}